package cn.edu.usst.cs.chat_room01;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Locale;
import java.util.Map;

@WebServlet(name = "chatServlet", value = "/chatroom")
public class ChatroomServlet extends HttpServlet implements ServletInterface {

    private JSONArray msgARR;
    private static final String REFERER = "chatroom.jsp";

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        msgARR = new JSONArray();
    }

    /**
     * 只能由{@code HelloServlet}请求，获取验证码
     *
     * @param req  an {@link HttpServletRequest} object that contains the request the client has made of the servlet
     * @param resp an {@link HttpServletResponse} object that contains the response the servlet sends to the client
     * @throws IOException
     */

    @Override
    protected synchronized void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getHeader("username_readonly");
        if(username == null) {
            HelloServlet.wrapMessage(resp,new JSONArray());
            return;
        }
        JSONArray temp = wrapChats(username);
        System.out.println(temp);
        HelloServlet.wrapMessage(resp, temp);
    }

    private JSONArray wrapChats(String username){
        JSONArray temp = new JSONArray();
        for (int i = 0; i < msgARR.length(); i++) {
            try {
                JSONObject obj = msgARR.getJSONObject(i);
                String sender = obj.getString("sender".toLowerCase(Locale.ROOT));
                String receiver = obj.getString("receiver");
                if (sender == null) throw new NullPointerException("sender is null");
                if (receiver == null) throw new NullPointerException("receiver is null");
                if(sender.equals(username)) continue;
                String err_message;
                VALID_RECEIVER:{
                    if(ALL_USER.equals(receiver)) {
                        break VALID_RECEIVER;
                    }
                    if(receiver.equals(username))
                        break VALID_RECEIVER;
                    System.out.println("hidden because of auth");
                    continue;
                }
                temp.put(obj);
            } catch (JSONException | NullPointerException e) {
                System.out.println("wrapping err"+e.getClass());
                return temp;
            }
        }
        return temp;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String message = HelloServlet.requestReadout(req);
        System.out.print(message);
        Map<String, String> msgMap = HelloServlet.parseFormSubmitMessage(message);
        System.out.print(msgMap);
        ADD:
        {
            String sender = msgMap.get("SENDER");
            String receiver = msgMap.get("RECEIVER");
            String message_content = msgMap.get("message");
            if (sender == null || receiver == null || message_content == null) break ADD;
            JSONObject jo = new JSONObject();
            jo.put("sender", sender);
            jo.put("receiver", receiver);
            jo.put("message", message_content);
            msgARR.put(jo);
            System.out.println();
            System.out.println(msgARR);
            req.getSession().setAttribute("info", "发送成功");
            req.getRequestDispatcher("chatroom.jsp").forward(req, resp);
            return;
        }
        req.getSession().setAttribute("info", "发送失败");
        req.getRequestDispatcher("chatroom.jsp").forward(req, resp);

    }
}
